import express from 'express';
import path from 'path'
import request from '../../util/request.js'
import formatTime from '../../util/formatTime.js'
import getMews from '../spider/modules/sina/sina_spider.js'
import {getResult} from '../../util/operateSql.js';
import get_news from '../spider/modules/sina/sina_spider.js';
import { getEnv } from '../../util/envConfig.js';

var router = express.Router();

const defaultParams = {
  status: true,
  interval: 3600
}

const targetUrl = 'https://s.weibo.com'
const urls = ['/top/summary?cate=realtimehot',
'/top/summary?cate=socialevent',
'/top/summary?cate=entrank']

let timer = null

const save = (url, type) => {
  return new Promise((resolve, reject) => {
    get_news(url, (e) => {
      if (e.code === 0) {
        const arr = e.data
        arr.shift()
        arr.forEach((item, index) => {
          const sql = `INSERT INTO spider.sina_siper_news (create_time, update_time, post_title, 
            post_url, post_hot, post_type) VALUES ('${formatTime()}', '${formatTime()}', '${item.title}',
             '${item.url}', ${item.hot}, '${type}') ON DUPLICATE KEY UPDATE  post_hot= if(values(post_hot) < ${item.hot},
              ${item.hot},values(post_hot) ), update_time=if(values(post_hot) < ${item.hot}, '${formatTime()}', values(update_time))`
            // 存数据库
            getResult(sql).then((result2) => {
              if (index === e.data.length - 1) {
                resolve('success')
              }
            }).catch(err => {
              return err
            })
        });
      } else {
        reject(e)
      }
    })
  });
}

const executeMiddle = (req,res,next) => {
  console.log(`output->middle`,)
  const params = req?.query || defaultParams
  let item = ''
  const interval = !params.interval ? 3600 * 1000 : parseInt(params.interval)
  let status = params.status === 'true' || params.status == true ? true : false
  if (params.type === 'hot') item = targetUrl + urls[0]
  else if (params.type === 'social') item = targetUrl + urls[1]
  else item = targetUrl + urls[2]
  
  // 使用本地代码，不请求自身
  // let rows = request(`${baseUrl}/spider/crawl/sina`)
  const run = () => {
    if (!params.type) {
      urls.forEach((url, index) => {
        const type = index === 0 ? 'hot' : (index === 1? 'social' : 'entrank')
        item = targetUrl + url
          save(item, type).then(r => {
          }).catch(err => {
          })
      })

    } else {
        save(item, params.type).then(r => {
        }).catch(err => {
        })
    }
  }

  if (status && !timer) {
    // 获取到新闻列表
    run()
    timer = setInterval(() => {  
      run()
    }, interval * 1000);
    req?req.result={code: 0, msg: 'opening'}:''
  } else if (!status) {
    clearInterval(timer)
    timer = null
    req?req.result={code: 500, msg: 'close'}:''
  } else {
    req?req.result={code: 500, msg: 'has opend'}:''
  }

  req?next():''

} 

// 开启自动执行
if (getEnv('ISAUTORUN')) {
  executeMiddle()
} 

router.get('/save/sina',executeMiddle, (req,res, next) => {
  res.json(req.app.locals.success(req.result))
})


export default router